<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateFacilityModelAPIRequest;
use App\Http\Requests\API\UpdateFacilityModelAPIRequest;
use App\Models\FacilityModel;
use App\Models\CityModel;

use App\Models\FacilityTicketModel;
use App\Repositories\FacilityModelRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Illuminate\Support\Facades\Log;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Illuminate\Http\Response;
use App\Http\Services\FacilityDTOBuilderService;
use Illuminate\Support\Facades\Storage;

/**
 * Class FacilityController
 * @package App\Http\Controllers\API
 */
class FacilityController extends AppBaseController
{
    /** @var  FacilityModelRepository */
    private $facilityModelRepository;

    /**
     * Store a newly created FacilityModel in storage.
     * POST /facilityModels
     *
     * @param CreateFacilityModelAPIRequest $request
     *
     * @return Response
     */
    public function store(FacilityModelRepository $repository)
    {
        $input = $this->request->all();
        $this->validateInputParams('store', $input);
        $cityId = $input['city_id'];
        $city = CityModel::where('id', $cityId)->first();
        if (empty($city)) {
            return $this->error(1, '城市ID非法');
        }

        Log::info("上传酒店");
        $input['city_name'] = $city->city;
        $input['payment'] = '';

        $model = $repository->create($input);

        return $this->sendResponse($model->toArray(), '操作成功');
    }

    /**
     * Store a newly created FacilityModel in storage.
     * POST /facilityModels
     *
     * @param CreateFacilityModelAPIRequest $request
     *
     * @return Response
     */
    public function uploadImage(FacilityModelRepository $repository)
    {
        Log::info("上传酒店");

        $path = '';
        $facilityId = $this->request->get('id');
        $image = $this->request->file('image', null);

        $facilityModel = $repository->findWithoutFail($facilityId);
        if (empty($facilityModel) || $facilityModel->status != 0) {
            return $this->sendError('没有找到设施或者已被删除');
        }
        $name = (string) $facilityModel->id;
        $fileName = '';
        if (!empty($image)) {
            $fileName = $image->getClientOriginalName();
            $image->storeAs($name, $fileName);
        }

        $flag = $this->request->get('delete_all', 0);
        $imageList = $facilityModel->images;
        if (empty($imageList)) {
            $imageList = [];
        } else {
            $imageList = json_decode($imageList, true);
        }
        if ($flag) {
            // 删除所有的图片
            $imageList = $facilityModel->images;
            $imageList = json_decode($imageList, true);
            if (!empty($imageList)) {
               $pathList = array_map(function ($v) {
                    $path = public_path($v);
                   @unlink($path);
                }, $imageList);
                $imageList = [];
                $facilityModel->images = json_encode($imageList);
            }
        }

        if (!empty($image)) {
            $path = "storage/" . $name . '/' . $fileName;
            $host = config('app.url');
            $imageList[] = $path;
            
            $path = $host . '/' . $path;
            $facilityModel->images = json_encode($imageList);
        }

        $facilityModel->save();

        return $this->sendResponse(['path' => $path], '上传成功');
    }

    /**
     * Display the specified FacilityModel.
     * GET|HEAD /facilityModels/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id, FacilityModelRepository $repository)
    {
        /** @var FacilityModel $facilityModel */
        $facilityModel = $repository->findWithoutFail($id);

        if (empty($facilityModel)) {
            return $this->sendError('Facility Model not found');
        }
        
        $ret = FacilityDTOBuilderService::build($facilityModel->toArray());

        return $this->sendResponse($ret, 'ok');
    }

    /**
     * Update the specified FacilityModel in storage.
     * PUT/PATCH /facilityModels/{id}
     *
     * @param  int $id
     * @param UpdateFacilityModelAPIRequest $request
     *
     * @return Response
     */
    public function update($id, FacilityModelRepository $repo)
    {
        $input = $this->request->all();
        $this->validateInputParams('update', $input);
        $cityId = $input['city_id'] ?? 0;
        
        if ($cityId) {
            $city = CityModel::where('id', $cityId)->first();
            if (empty($city)) {
                return $this->error(1, '城市ID非法');
            }

            $input['city_name'] = $city->city;
        }

        $model = $repo->findWithoutFail($id);

        if (empty($model) || $model->status != 0) {
            return $this->sendError('设施不存在或已被删除');
        }

        $model->updateRecord($id, $input);

        return $this->sendResponse([], '操作成功');
    }

    /**
     * Remove the specified FacilityModel from storage.
     * DELETE /facilityModels/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        /** @var FacilityModel $facilityModel */
        $facilityModel = $this->facilityModelRepository->findWithoutFail($id);

        if (empty($facilityModel)) {
            return $this->sendError('Facility Model not found');
        }

        $facilityModel->delete();

        return $this->sendResponse($id, 'Facility Model deleted successfully');
    }

    public function search(FacilityModelRepository $repo)
    {
        $input = $this->request->all();

        $searchOptions = $this->normalizeSearchOptions();
        $sortOptions = $this->normalizeSortOptions();
        $cityId = array_get($input, 'city_id', 0);
        !empty($cityId) && $searchOptions['city_id'] = $cityId;
        $cateogyId = array_get($input, 'category_id', 0);
        !empty($cateogyId) && $searchOptions['category_id'] = $cateogyId;
        $searchOptions['status'] = 0;

        $ret = $repo->search($searchOptions, $sortOptions);

        $lists = $ret['lists'];
        if (count($lists) == 0) {
            return $this->success(['lists' => []]);
        }

        $lists = FacilityDTOBuilderService::buildList($lists);
        $ret['lists'] = $lists;

        return $this->success($ret);
    }

    /**
     * Remove the specified AdminModel from storage.
     * DELETE /adminModels/{id}
     *
     * @param  int $id
     *
     */
    public function batchDelete()
    {
        $ids = $this->request->get('facility_ids');
        if (empty($ids)) {
            return $this->sendError('id不为空');
        }

        $ids = explode(',', $ids);
        FacilityModel::whereIn('id', $ids)->update(['status' => 2]);
        // 断开酒店优惠券的联系
        FacilityTicketModel::whereIn('facility_id', $ids)->delete();

        return $this->success([], '删除成功');
    }

    /**
     * 参数验证规则
     * self::VALID_RULES[__FUNCTION__]
     */
    const VALID_RULES = [
        'store' => [
            'category_id' => 'required|int|min:10|max:12',
            'city_id' => 'required|int',
            'price' => 'nullable|json',
            'working_time' => 'required|string|min:1',
            'tel' => 'required|string|min:1',
            'description' => 'required|string|min:1',
            'name' => 'required|string|min:1',
            'address' => 'required|string|min:1',
            'food_brand' => 'nullable|json',
            'brand' => 'nullable|json',
        ],
        'update' => [
            'category_id' => 'int|min:10|max:12',
            'city_id' => 'int',
            'price' => 'nullable|json',
            'working_time' => 'string|min:1',
            'tel' => 'string|min:1',
            'name' => 'string|min:1',
            'address' => 'string|min:1',
            'description' => 'required|string|min:1',
            'food_brand' => 'nullable|json',
            'brand' => 'nullable|json',
        ],
    ];
}
